package com.company.common;

import com.company.model.request.PageQuery;
import com.company.model.result.PageResult;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;

/**
 * Created by tu on 2017/7/6.
 */
public class PageUtils {

  public static final int DEFAULT_PAGE = 0;

  public static final int DEFAULT_PAGESIZE = 20;

  public static final String PERCENT = "%";

  /**
   * 分页查询结果包装
   */
  public static <T> PageResult<T> wrapPageResult(Page<T> page) {
    PageResult<T> pageResult = new PageResult<>();
    pageResult.setTotal(page.getTotalElements());
    pageResult.setContent(page.getContent());
    pageResult.setPageNo(page.getNumber());
    pageResult.setPageSize(page.getSize());
    pageResult.setTotalPage(page.getTotalPages());
    return pageResult;
  }

  /**
   * 分页查询结果包装
   */
  public static <T> PageResult<T> wrapPageResult(Page<T> page, Pageable pageable) {
    PageResult<T> pageResult = new PageResult<>();
    pageResult.setTotal(page.getTotalElements());
    pageResult.setContent(page.getContent());
    pageResult.setPageNo(pageable.getPageNumber());
    pageResult.setPageSize(pageable.getPageSize());
    pageResult.setTotalPage(page.getTotalPages());

    return pageResult;
  }

  /**
   * 分页查询结果包装
   */
  public static <T> PageResult<T> wrapPageResult(Page<T> page, PageQuery pageQuery) {
    PageResult<T> pageResult = new PageResult<>();
    pageResult.setTotal(page.getTotalElements());
    pageResult.setContent(page.getContent());
    pageResult.setTotalPage(page.getTotalPages());

    pageResult.setPageNo(pageQuery.getPage());
    pageResult.setPageSize(pageQuery.getPageSize());

    return pageResult;
  }

  /**
   * 获取分页查询条件
   */
  public static PageRequest initPageRequest(PageQuery pageQuery) {
    int pageSize =
        pageQuery.getPageSize() == null ? PageUtils.DEFAULT_PAGESIZE : pageQuery.getPageSize();
    int page = pageQuery.getPage() == null ? PageUtils.DEFAULT_PAGE : pageQuery.getPage() - 1;
    PageRequest pageRequest = new PageRequest(page, pageSize);
    return pageRequest;
  }
}
